package com.tang.Dao;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import com.tang.Utils.JDBCUtils;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.*;

import java.util.Arrays;
import java.util.List;
import com.tang.pojo.User;

import java.sql.*;

public class BaseDao {

    private QueryRunner qr;
    public BaseDao(){
     qr=new QueryRunner();
    }
    public void update(String sql,Object... args){
        Connection con=null;
        try {
            con = JDBCUtils.getThreadConnetion();
        }catch(SQLException e){
            e.printStackTrace();
        }
        try {
            qr.update(con,sql,args);
        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public <T> T queryforOne(Class<T>type,String sql,Object... args){
            Connection con=null;
            try {
                con = JDBCUtils.getThreadConnetion();
            }catch(SQLException e){
                e.printStackTrace();
            }
        ResultSetHandler<T> rsh=new BeanHandler<T>(type);
        T obj=null;
        try {
            obj = qr.query(con,sql, rsh,args);
        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return obj;
    }
    public <T> List<T> queryforMul(Class<T> type,String sql,Object... args){
        Connection con=null;
        try {
            con = JDBCUtils.getThreadConnetion();
        }catch(SQLException e){
            e.printStackTrace();
        }
        BeanListHandler<T> blh=new BeanListHandler<T>(type);
        List<T> objs=null;
        try {
            objs = qr.query(con,sql, blh,args);
        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return objs;
    }
    public long queryforSingle(String sql,Object... args){
        Connection con=null;
        try {
            con = JDBCUtils.getThreadConnetion();
        }catch(SQLException e){
            e.printStackTrace();
        }
        ScalarHandler<Long> sh=new ScalarHandler<Long>();
        long info=0;
        try {
           info = qr.query(con,sql, sh,args);
        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return info;
    }
}
